package com.nowcoder.community.controller;
import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.dao.MessageMapper;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.XaCommunityUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.*;

import static com.nowcoder.community.util.XaCommunityConstant.*;

@Controller
public class MessageController {
    @Resource
    private MessageService messageService;
    @Resource
    private HostHolder hostHolder;
    @Resource
    private UserService userService;
    private User getLetterTarget(String conversationId){
        //因为conversationId格式是 id1_id2 因此用split将他两分开
        String[] ids=conversationId.split("_");
        int id0=Integer.parseInt(ids[0]);
        int id1=Integer.parseInt(ids[1]);
        if(hostHolder.getUser().getId()==id0){
            //当前用户id和发件人id一样 返回目标用户
            return userService.findUserById(id1);
        }
        else return userService.findUserById(id0);//否则返回当前发件用户
    }
    //获取私信目标用户
    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                //私信列表中的私信必须是  收件id为当前用户id，且状态为未读
                if (hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }
    //获取私信列表的id整合为列表
    @GetMapping("/letter/list")
    //1.私信列表
    public String getLetterList(Model model, Page page){
        //0.获取全局用户
        User user = hostHolder.getUser();
        
        //1.首先设置分页信息
        page.setPath("/letter/list");
        page.setLimit(5);
        page.setRows(messageService.findConversationCount(user.getId()));
        
        //2. 查询会话列表
        //2.1 获取会话列表
        List<Message> conversationList=messageService.findConversations(
                user.getId(), page.getOffset(), page.getLimit());
        
        //2.2 设置会话数组---获取的会话列表拆解为map对象
        List<Map<String, Object>> conversations = new ArrayList<>();
        if (conversationList != null) {
            for(Message message:conversationList){

                //3. 封装map中装私信及其对应的私信人
                Map<String,Object>map=new HashMap<>();
                map.put("conversation",message);
                map.put("letterCount",messageService.findLetterCount(message.getConversationId()));
                map.put("unreadCount",messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));
                
                //4.获取收信人
                int targetId= user.getId()== message.getFromId()? message.getToId(): message.getFromId();
                map.put("target",userService.findUserById(targetId));

                conversations.add(map);
            }
        }
        model.addAttribute("conversations",conversations);

        //4.查询未读私信数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(),null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);

        return "/site/letter";
    }
    @GetMapping("/letter/detail/{conversationId}")
    //2.查询私信详情
    public String getLetterDetail(@PathVariable("conversationId")String conversationId,
                                  Page page,Model model) {
        //1. 设置分页信息
        //1.1 设置分页限制
        page.setLimit(5);
        //1.2 设置分页路径
        page.setPath("/letter/detail/" + conversationId);
        //1.3 设置分页总条数
        page.setRows(messageService.findLetterCount(conversationId));
        
        
        //2.查询私信列表，并封装到model中
        List<Message>letterList =messageService.findLetters(conversationId, 
                page.getOffset(), page.getLimit());
        List<Map<String ,Object>>letters=new ArrayList<>();
        
        if(letterList!=null){
            for (Message message:letterList){
                Map<String,Object>map=new HashMap<>();
                map.put("letter",message);
                map.put("fromUser",userService.findUserById(message.getFromId()));
                letters.add(map);
            }
        }
        
        model.addAttribute("letters",letters);
        
        //3.添加私信目标
        model.addAttribute("target",getLetterTarget(conversationId));
        
        //4.获取letter队列中的所有id  --查看私信详情页之后需要设置已读
        List<Integer>ids=getLetterIds(letterList);
        
        if(!ids.isEmpty()){
            messageService.readMessage(ids);
        }
        return "/site/letter-detail";
    }
    @PostMapping("/letter/send") 
    @ResponseBody
    //3.发送私信
    public String sendLetter(String toName,String content){
        //1.获取目标用户
        User target=userService.findUserByName(toName);
        if(target==null){
            //1.1用户不存在，发送1：不存在的码
            return XaCommunityUtil.getJSONString(1, "目标用户不存在!");
        }
        
        //2.创建信息模板
        Message message=new Message();
        //2.1设置信息的收件和发件人
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        //2.2设置会话id  小的在前
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        //2.3设置信息的创建日期的内容
        message.setContent(content);
        message.setCreateTime(new Date());
        message.setStatus(0);//这个不写也默认是0
        messageService.addMessage(message);

        //3.发送成功码
        return XaCommunityUtil.getJSONString(0);
    }
    @PostMapping( "/message/delete")
    @ResponseBody
    //4.删除私信
    public String deleteMessage(int id) {
        messageService.deleteMessage(id);
        return XaCommunityUtil.getJSONString(0);
    }
    private Map<String,Object> getMessageVO(User user,String topic){
        Message message=messageService.findLatestNotice(user.getId(),topic);
        
        if(message!=null){
            Map<String,Object>messageVO=new HashMap<>();
            //通过message获取data
            messageVO.put("message",message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);
            
            //解析data来封装Vo结果实例
            messageVO.put("user",userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType",data.get("entityType"));
            messageVO.put("entityId",data.get("entityId"));
            messageVO.put("postId",data.get("postId"));
            int count= messageService.findNoticeCount(user.getId(), topic);
            messageVO.put("count",count);

            int unread=messageService.findNoticeUnreadCount(user.getId(), topic);
            messageVO.put("unread",unread);
            return messageVO;
        }
        
        return null;
    }
    //获取封装好的messageVO
    @GetMapping("/notice/list")
    public String getNoticeList(Model model){
        User user=hostHolder.getUser();
        
        // 查询评论类通知---将评论类通知封装，放进模型类
        model.addAttribute("commentNotice",getMessageVO(user,TOPIC_COMMENT));
        //查询点赞类通知---将点赞类通知封装，放进模型类
        model.addAttribute("likeNotice",getMessageVO(user,TOPIC_LIKE));
        //查询关注类通知---将关注类通知封装，放进模型类
        model.addAttribute("followNotice",getMessageVO(user,TOPIC_FOLLOW));
        
        int letterUnreadCount=messageService.
                findLetterUnreadCount(user.getId(), null);
        int noticeUnreadCount=messageService.
                findNoticeUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);
        return "/site/notice";
    }
    @GetMapping("/notice/detail/{topic}")
    public String getNoticeDetail (@PathVariable("topic") String topic,Page page,Model model){
        User user=hostHolder.getUser();
        
        //设置分页属性
        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.findNoticeCount(user.getId(), topic));

        List<Message> noticeList = messageService.findNotices(user.getId(), topic, page.getOffset(), page.getLimit());
        List<Map<String, Object>> noticeVoList = new ArrayList<>();
        //解析noticeList到VoList
        
        if(noticeList!=null){
            for(Message notice:noticeList){
                Map<String,Object>map=new HashMap<>();
                //通知  
                map.put("notice",notice);
                //内容
//                Map<String,Object>data=JSONObject.parseObject(
//                        HtmlUtils.htmlEscape(notice.getContent()), HashMap.class);
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                //解析内容
                map.put("user",userService.findUserById((Integer) data.get("userId")));
                map.put("entityType",data.get("entityType"));
                map.put("entityId",data.get("entityId"));
                map.put("postId",data.get("postId"));
                //通知作者
                map.put("fromUser",userService.findUserById(notice.getFromId()));
                noticeVoList.add(map);
            }
        }
        model.addAttribute("notices",noticeVoList);
        //设置已读
        List<Integer>ids=getLetterIds(noticeList);
        if(!ids.isEmpty()){
            messageService.readMessage(ids);
        }
        
        return "/site/notice-detail";
    }
}